package com.pair.micro.common.configPool;

import com.pair.micro.common.utils.MicroSystemUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * @Author:xubz
 * @Date:2023/4/6 16:48
 */
public class MicroThreadConfig {

    @Value("${micro.threadpool.threadnameprefix}")
    private String threadNamePrefix;

    // 最大可用的CPU核数
    public static int processors = MicroSystemUtil.availableProcessors();

    // 线程最大的空闲存活时间，单位为秒
    public static int keepalivetime = 60;

    // 任务缓存队列长度
    private static int queueCapacity = 100;

    @Bean(name = "microExecutor")
    public ThreadPoolTaskExecutor microExecutor() {

        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 线程核心数目
        threadPoolTaskExecutor.setCorePoolSize(processors * 2);
        threadPoolTaskExecutor.setKeepAliveSeconds(keepalivetime);
        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
        // 最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(processors * 4);
        // 配置队列大小
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        // 配置线程池前缀
        threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
        // 配置拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 数据初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
